<template>
  <div>
    <bread-crumb two="商品管理" three="商品分类"></bread-crumb>

    <!-- 卡片区 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- table表格 -->
      <el-table :data="catList" style="width: 99%" row-key="cat_id" border>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column label="排序" width="280">
          <template slot-scope="info">
            <el-tag v-if="info.row.cat_level===0">一级</el-tag>
            <el-tag v-else-if="info.row.cat_level===1" type="success">二级</el-tag>
            <el-tag v-else type="danger">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <el-row slot-scope="info">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(info.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="editDel(info.row.cat_id)"
            >删除</el-button>
          </el-row>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querycdt.pagenum"
        :page-size="querycdt.pagesize"
        :page-sizes="[5, 10, 15]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tot"
      ></el-pagination>
    </el-card>

    <!-- Dialog添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addDialog" width="50%" @close="resetForm">
      <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类上级" prop="selectTwoCat">
          <!--
            value:上级分类级联器value值的体现，
            lable:上级分类显示的内容
            checkStrictly:允许选择任意级别的分类
          -->
          <el-cascader
            v-model="addForm.selectTwoCat"
            :options="catListTwo"
            :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', checkStrictly: true}"
            clearable
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCat">确 定</el-button>
      </div>
    </el-dialog>

    <!-- Dialog编辑 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialog"
      width="50%"
      @close="editReset($refs.editFormRef)"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="分类名称" label-width="100px" prop="cat_name">
          <el-input v-model="editForm.cat_name" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editKinds">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.renderList()
  },
  data () {
    return {
      // 接收数据分类列表
      querycdt: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      catList: [],
      tot: 0,

      // 添加分类
      addDialog: false,
      // cat_pid父级ID，cat_levle新分类级别（0,1,2）
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
        selectTwoCat: []
      },
      catListTwo: [],

      // 表单校验
      addFormRules: {
        cat_name: [{ required: true, message: '分类名称必填', trigger: 'blur' }]
      },

      // 编辑表单数据
      editDialog: false,
      editForm: {
        cat_id: '',
        cat_name: ''
      },

      // 编辑表单校验
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 获取分类
    async renderList () {
      const { data: dt } = await this.$http.get('categories', {
        params: this.querycdt
      })
      // 获取内容请求
      // console.log(dt)
      this.tot = dt.data.total
      this.catList = dt.data.result
    },

    // 分页类事件
    handleSizeChange (newSize) {
      // console.log('当前每页数量', newSize)
      this.querycdt.pagesize = newSize
      this.renderList()
    },
    handleCurrentChange (newCurrent) {
      // console.log('当前页数', newCurrent)
      this.querycdt.pagenum = newCurrent
      this.renderList()
    },

    // 添加分类事件
    // 显示添加框
    async showAddDialog () {
      // type只需要到2，因为第三级是最底层，不需要再往下分类了
      const { data: dt } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      console.log(dt.data)
      this.catListTwo = dt.data
      this.addDialog = true
    },

    // 当分类被选中后的回调函数
    handleChange () {
      // 捕获上级分类的cat_id值————>this.addForm.selectTwoCat 存储在数之中
      // console.log(this.addForm.selectTwoCat)
      // 数组长度为0时，为一级，长度为1时，为二级，长度为2时，为三级
      const num = this.addForm.selectTwoCat.length
      const twocat = this.addForm.selectTwoCat
      if (num === 0) {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      } else {
        this.addForm.cat_pid = twocat[num - 1]
        this.addForm.cat_level = num
      }
    },

    // 添加分类请求
    addCat () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: dt } = await this.$http.post('categories', this.addForm)
          console.log(dt)
          this.addDialog = false
          this.$message.success(dt.meta.msg)
          this.renderList()
        }
      })
    },

    // 添加重置表单
    resetForm () {
      this.$refs.addFormRef.resetFields()
      this.addForm.cat_pid = this.addForm.cat_level = 0
    },

    // 显示编辑Dialog框
    showEditDialog (edit) {
      this.editDialog = true
      // console.log(edit)
      this.editForm = edit
    },

    // 收集编辑后的修改数据
    editKinds () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: dt } = await this.$http.put(
            'categories/' + this.editForm.cat_id,
            this.editForm
          )
          // 获取编辑后响应
          // console.log(dt)
          this.$message.success(dt.meta.msg)
          this.editDialog = false
          this.renderList()
        }
      })
    },
    // 关闭编辑框重置表单
    editReset (form) {
      if (form) {
        form.resetFields()
        this.renderList()
      }
    },

    editDel (id) {
      this.$confirm('确认要删除该分类么吗', '删除分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: dt } = await this.$http.delete('categories/' + id)
          // return this.$message.success(dt.meta.msg)
          // console.log(dt)
          this.$message.success(dt.meta.msg)
          this.renderList()
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="less" scoped>
</style>
